using System.Text;
using JtwTestWebApi.Models;
using JtwTestWebApi;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Todo;
using Todo.WebConfig;

var builder = WebApplication.CreateBuilder(args);

//添加认证方式
// builder.Services.AddAuthorization();
// builder.Services.AddAuthentication("Bearer").AddJwtBearer();


// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// 注册 db context
builder.Services.AddDbContext<ApplicationDBContext>(options =>
    options.UseSqlServer(builder.Configuration["DefaultConnection"]));


// 依赖注入
builder.Services.AddScoped<IUser, UserServiceImpl>();
builder.Services.AddScoped<ITodo, TodoServiceImpl>();
builder.Services.AddSingleton(new JwtHelper());
builder.Services.AddSingleton<WebApiConfig>();

var jwtConfig = new JwtConfig();
builder.Configuration.Bind("Jwt",jwtConfig);
var jwtHelper = new JwtHelper() {
        JwtConfig = jwtConfig
    };
//将JwtHelper添加到Services里面
builder.Services.AddSingleton<JwtHelper>(jwtHelper);
// jwtHelper.AddJwtService(builder.Services);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => {
        //获取密钥
        var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Jwt:SecretKey"]);
        options.TokenValidationParameters = new TokenValidationParameters
        {
            //验证token发布者  只有后端Issuer发出的Token才被接受
            ValidateIssuer = true,
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            //token持有者
            ValidateAudience = true ,
            ValidAudience=builder.Configuration["Jwt:Audience"],
            //验证token是否过期
            ValidateLifetime=true ,
            //传如私钥并加密
            IssuerSigningKey=new SymmetricSecurityKey(secretByte)

        };
    });
builder.Services.AddCors(cors =>
{
    cors.AddPolicy("CorsPolicy", policy =>
    {
        policy.AllowAnyOrigin().WithOrigins("GET", "POST", "PUT", "DELETE", "HEAD").AllowAnyHeader();
    });
});
var app = builder.Build();


// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthentication();
app.UseCors("CorsPolicy");
app.UseAuthorization();

app.MapControllers();

// 确保数据库上下文已初始化
using (var serviceScope = app.Services.CreateScope())
{
    var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDBContext>();
    context.Database.Migrate(); // 确保应用最新的迁移
}


//调用中间件：UseAuthentication（认证），必须在所有需要身份认证的中间件前调用，比如 UseAuthorization（授权）。
app.UseAuthentication();


app.Run();